package com.thenie.chat.controller;

import cn.hutool.json.JSONUtil;
import com.thenie.chat.util.WebSocketUtil;
import com.thenie.chat.vo.DialogRandomMessage;
import com.thenie.chat.vo.RespBean;
import com.thenie.chat.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 随机匹配聊天 WS
 * @author nieshiji
 * @date 2022/7/31 16:52
 */
@Component
@Slf4j
public class DialogRandomSocketHandler extends AbstractWebSocketHandler {

    public static final Map<String, WebSocketSession> RANDOM_SESSION_MAP = new ConcurrentHashMap<>(32);

    /**
     * 连接成功后调用
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String userId = WebSocketUtil.getUserId(session);
        RANDOM_SESSION_MAP.put(userId,session);
    }


    /**
     * 转发消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
            //获取消息
            String jsonMessage = message.getPayload();
            DialogRandomMessage dialogRandomMessage = JSONUtil.toBean(jsonMessage, DialogRandomMessage.class);
            //获取接收方id
            String toFriendId = dialogRandomMessage.getToId();
            WebSocketSession toSession = RANDOM_SESSION_MAP.get(toFriendId);

            if (toSession != null) {
                TextMessage msg = new TextMessage(JSONUtil.toJsonStr(
                        RespBean.success(RespBeanEnum.SEND_ONE_MESSAGE, dialogRandomMessage)
                ));
                //发送给对方
                toSession.sendMessage(msg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) {
    }

    /**
     * WS 连接出错时调用
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("webSocket连接出错", exception);
    }

    /**
     * 连接关闭后调用
     *
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        //通知下线
        String userId = WebSocketUtil.getUserId(session);
        //删除本地session
        RANDOM_SESSION_MAP.remove(userId);
    }

    /**
     * 是否支持分片消息
     *
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}
